package com.weituotian.moudle.member.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.result.Result;
import com.weituotian.core.utils.FileUtil;
import com.weituotian.core.utils.ShiroUtil;
import com.weituotian.moudle.front.service.ICommentService;
import com.weituotian.moudle.member.entity.Member;
import com.weituotian.moudle.member.entity.enums.SexEnum;
import com.weituotian.moudle.member.entity.vo.MemberVo;
import com.weituotian.moudle.member.service.IAttachmentService;
import com.weituotian.moudle.member.service.IMemberService;
import com.weituotian.system.entity.User;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 会员个人中心控制器
 * Created by ange on 2017/2/22.
 */
@Controller
@RequestMapping("${memberPath}/my")
public class MemberController extends BaseController {

    private final IMemberService memberService;

    private final IAttachmentService attachmentService;

    private final ICommentService commentService;

    @Value("${member.avater}")
    protected String avaterPath;

    @Autowired
    public MemberController(IMemberService memberService, IAttachmentService attachmentService, ICommentService commentService) {
        this.memberService = memberService;
        this.attachmentService = attachmentService;
        this.commentService = commentService;
    }

    @ModelAttribute
    public void initUrl(Model model) {
        String contextPath = this.getContextPath();
        model.addAttribute("avatar_url", contextPath + memberPath + "/my/avaterupload");
    }

    @InitBinder
    public void initBinder(WebDataBinder binder) {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);

        binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));   //true:允许输入空值，false:不能为空值
    }


    /**
     * 后台首页
     *
     * @return
     */
    @RequestMapping("/index")
    public String index() {
        return "system/index/index";
    }

    /**
     * 会员后台欢迎页
     *
     * @return
     */
    @RequestMapping("/welcome")
    public String welcome() {
        return null;
    }

    /**
     * 完善资料,修改个人资料
     *
     * @return
     */
    @RequestMapping("/edit")
    public String information(Model model) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        Member member = memberService.findById(user.getId());
        /*if (member.getAvatar() != null) {
            member.setAvatar(getAvatarPath() + member.getAvatar());
        }*/

        model.addAttribute("member", member);

        model.addAttribute("sexEnum", SexEnum.values());

        String contextPath = this.getContextPath();
        model.addAttribute("form_url", contextPath + memberPath + "/my/doedit");

        model.addAttribute("pageName", "我的信息");
        return "member/my/edit";
    }

    @RequestMapping(value = "/doedit", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object doedit(MemberVo memberVo) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User) subject.getPrincipal();

        try {
            memberService.updateByDto(memberVo, user.getId());
        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        return renderSuccess("修改成功");
    }

    /**
     * 上传文件
     *
     * @param file
     * @param request
     * @return
     */
    @RequestMapping(value = "/avaterupload", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object uploadImage(@RequestParam("file") MultipartFile file, HttpServletRequest request) {
//        http://blog.csdn.net/orange_ph/article/details/52027987
        //https://zhidao.baidu.com/question/327533541683411045.html
//      http://blog.csdn.net/cheung1021/article/details/7084673/

        System.out.println("开始");
        String path = request.getSession().getServletContext().getRealPath(avaterPath);//在磁盘上的绝对路径
        System.out.println(path);

//        String fileName = file.getOriginalFilename();
//        String fileName = new Date().getTime()+".jpg";
        String newFileName = FileUtil.generateNewFileName(file.getOriginalFilename());

        File targetFile = new File(path, newFileName);
        if (!targetFile.exists()) {
            targetFile.mkdirs();
        }

        //保存
        try {
            file.transferTo(targetFile);

            //写入附件表
            attachmentService.addTemp(file, targetFile);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("服务器保存文件失败");
        }

        String fileUrl = request.getContextPath() + avaterPath + "/" + newFileName;

        Map<String, String> urlMap = new HashMap<>();
        urlMap.put("url", fileUrl);
        urlMap.put("filename", newFileName);

        Result result = renderSuccess("");
        result.setObj(urlMap);
        return result;
    }

    @RequestMapping(value = "/addcomment", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object addComment(Integer videoId, String content) {
        try {
            User currentUser = ShiroUtil.getCurrentUser();
            int userId = currentUser.getId();
            commentService.addComment(userId, content, videoId);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("发送失败");
        }
        return renderSuccess("评论成功");
    }


}
